package com.enation.app.javashop.consumer.shop.promotion;

import com.enation.app.javashop.consumer.core.event.CustomerPushMessageEvent;
import com.enation.app.javashop.core.promotion.activitymessage.model.dos.ActivityMessageDO;
import com.enation.app.javashop.core.promotion.activitymessage.model.dos.ActivityMessageRecordDO;
import com.enation.app.javashop.core.promotion.activitymessage.service.ActivityMessageManager;
import com.enation.app.javashop.core.system.enums.WechatMiniproTemplateTypeEnum;
import com.enation.app.javashop.core.system.model.dto.MiniproMsgDataDTO;
import com.enation.app.javashop.core.system.model.dto.MiniproSendMsgDTO;
import com.enation.app.javashop.core.system.service.WechatMiniproTemplateManager;
import com.enation.app.javashop.framework.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class customerPushMessageInvokeConsumer implements CustomerPushMessageEvent {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ActivityMessageManager activityMessageManager;
    @Autowired
    private WechatMiniproTemplateManager wechatMiniproTemplateManager;


    @Override
    public void customerPushMessageInvoke(ActivityMessageDO activityMessageDO) {
        try {
            MiniproSendMsgDTO miniproSendMsgDTO;
            // 1.0 查询已订阅的人
            List<ActivityMessageRecordDO> activityMessageRecordDOList = activityMessageManager.getActivityMessageRecordDO(activityMessageDO.getActivityId());
            // 1.1 给订阅的人推消息
            for (ActivityMessageRecordDO activityMessageRecordDO : activityMessageRecordDOList) {
                // 1.1.1 封装data参数
                Map<String, Object> dataMap = new HashMap<>();
                // 活动名称
                dataMap.put("thing6", MiniproMsgDataDTO.build(activityMessageDO.getActivityName()));
                // 活动内容
                dataMap.put("thing7", MiniproMsgDataDTO.build(activityMessageDO.getActivityContent()));
                // 开始时间
                dataMap.put("date3", MiniproMsgDataDTO.build(DateUtil.toString(activityMessageDO.getActivityTime(), "yyyy-MM-dd HH:mm:ss")));
                // 温馨提示
                dataMap.put("thing10", MiniproMsgDataDTO.build(activityMessageDO.getReminder()));
                // 封装消息
                miniproSendMsgDTO = new MiniproSendMsgDTO(activityMessageRecordDO.getOpenId(), WechatMiniproTemplateTypeEnum.ACTIVITYSTART_NOTICE,
                       dataMap, "");
                wechatMiniproTemplateManager.send(miniproSendMsgDTO);
                logger.info("活动推送消息,发送成功");
            }
        }catch (Exception e){
            this.logger.error("活动推送消息失败:", e);
        }
    }
}
